package com.richinfo.util;

import com.richinfo.common.config.Global;
import com.richinfo.entity.SmsInfo;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 短信接口工具类
 * @author Administrator
 */
@Component
public class SmsUtils {
	private static final String URL = Global.getConfig("sms.iap.url");
	
	private static final String UID = Global.getConfig("sms.iap.uid");
	
	private static final String PASSWORD = Global.getConfig("sms.iap.password");
	
	private static final String EXTEND_NUM = Global.getConfig("sms.iap.extendNum");
	
    private static Logger log = Logger.getLogger(SmsUtils.class);

//    public static SmsInfoService smsInfoService = SpringContextHolder.getBean(SmsInfoService.class);

    private static String        key1 = "<message>";
    private static String        key2 = "</message>";
    private static String        key3 = "sessionId";

    public static String login(String uid, String password) {
        uid = StringUtils.isBlank(uid) ? UID : uid;
        password = StringUtils.isBlank(password) ? PASSWORD : password;

        OrderedMap params = new LinkedMap();
        params.put("uid", uid);
        params.put("password", password);
        Map<String,Object> sessionMap = WebServiceInvoke.invoke(URL, "login", params);
        String sessionId = (String) sessionMap.get("message");

        log.info("SmsUtils.login.sessionId:" + sessionId);

        return sessionId;
    }

    public static Map<String,Object> send(String content, String receivers, String extendsNum) {

        Assert.notNull(content);
        Assert.notNull(receivers);
        extendsNum = StringUtils.isBlank(extendsNum) ? EXTEND_NUM : extendsNum;

        //获取sessionId
        String sessionId = login("", "");
        Assert.notNull(sessionId);

        //发送短信
        OrderedMap params = new LinkedMap();
        params.put(key3, sessionId);
        params.put("content", content);
        params.put("receivers", receivers);
        params.put("extendsNum", extendsNum);
        Map<String,Object> messageMap = WebServiceInvoke.invoke(URL, "send", params);
        String messageId = (String) messageMap.get("message");
        log.info("SmsUtils.send.messageId:" + sessionId);
        //记录短信
        SmsInfo sms = new SmsInfo();
        sms.setSessionId(sessionId);
        sms.setMessageId(messageId);
        sms.setContent(content);
        sms.setReceivers(receivers);
        sms.setExtendsNum(extendsNum);
//        smsInfoService.save(sms);

        //退出
        int result = logout(sessionId);
        //退出失败，强制退出
        if (result == 0) {
            forceLogout("", "");
        }

        return messageMap;
    }

    public static int logout(String sessionId) {
        Assert.notNull(sessionId);

        OrderedMap params = new LinkedMap();
        params.put(key3, sessionId);
        int result = WebServiceInvoke.invokeInteger(URL, "logout", params);

        return result;
    }

    public static int forceLogout(String uid, String password) {
        uid = StringUtils.isBlank(uid) ? UID : uid;
        password = StringUtils.isBlank(password) ? PASSWORD : password;

        OrderedMap params = new LinkedMap();
        params.put("uid", uid);
        params.put("password", password);
        int result = WebServiceInvoke.invokeInteger(URL, "forceLogout", params);

        return result;
    }

    public static SmsInfo resend(String content, String receivers, String extendsNum) {
        Assert.notNull(content);
        Assert.notNull(receivers);
        extendsNum = StringUtils.isBlank(extendsNum) ? EXTEND_NUM : extendsNum;

        //获取sessionId
        String sessionId = login("", "");
        Assert.notNull(sessionId);

        //发送短信
        OrderedMap params = new LinkedMap();
        params.put(key3, sessionId);
        params.put("content", content);
        params.put("receivers", receivers);
        params.put("extendsNum", extendsNum);
        Map<String,Object> messageMap = WebServiceInvoke.invoke(URL, "send", params);
        String messageId = (String) messageMap.get("message");

        SmsInfo sms = new SmsInfo();
        sms.setSessionId(sessionId);
        sms.setMessageId(messageId);

        //退出
        int result = logout(sessionId);
        //退出失败，强制退出
        if (result == 0) {
            forceLogout("", "");
        }

        return sms;

    }

    public static List<SmsInfo> getMsgReport(String sessionId) throws DocumentException {
        Assert.notNull(sessionId);

        OrderedMap params = new LinkedMap();
        params.put(key3, sessionId);
        Map<String,Object> resultMap = WebServiceInvoke.invoke(URL, "login", params);
        String result = (String) resultMap.get("message");

        //		String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
        //				"<messages>"+
        //				key1+
        //				"<sysUid>123456</sysUid>"+
        //				"<mobile>123</mobile>"+
        //				"<status>123</status>"+
        //				"<clientId>234</clientId>"+
        //				key2+
        //				key1+
        //				"<sysUid>1234567</sysUid>"+
        //				"<mobile>345346</mobile>"+
        //				"<status>23454</status>"+
        //				"<clientId>67</clientId>"+
        //				key2+
        //				"</messages>";
        List<SmsInfo> list = new ArrayList<SmsInfo>();
        if (!StringUtils.equals(result, "0") && !StringUtils.equals(result, "-1")) {
            Element root = XmlUtil.getDomBody(result);
            Iterator messages = root.elementIterator("message");
            while (messages.hasNext()) {
                SmsInfo sms = new SmsInfo();
                Element element = (Element) messages.next();
                sms.setSessionId(sessionId);
                sms.setMessageId(element.elementTextTrim("clientId"));
                sms.setReason(element.elementTextTrim("status"));
                sms.setCode(element.elementTextTrim("mobile"));
                sms.setUid(element.elementTextTrim("sysUid"));
                sms.setState("0");
                list.add(sms);
            }
        } else if (StringUtils.equals(result, "0")) {

        } else if (StringUtils.equals(result, "-1")) {

        }

        return list;
    }

    public static void main(String[] args) throws DocumentException {
        String ss = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<messages>" + key1
                    + "<sysUid>接口用户编号</sysUid>" + "<mobile>手机号码</mobile>"
                    + "<status>返回状态描述</status>" + "<clientId>流水号</clientId>" + key2 + key1
                    + "<sysUid>接口用户编号</sysUid>" + "<mobile>手机号码</mobile>"
                    + "<status>返回状态描述</status>" + "<clientId>流水号</clientId>" + key2 + "</messages>";

        Element root = XmlUtil.getDomBody(ss);
        Iterator message = root.elementIterator("message");
        while (message.hasNext()) {
            SmsInfo sms = new SmsInfo();
            Element element = (Element) message.next();
            sms.setSessionId("");
            sms.setMessageId(element.elementTextTrim("clientId"));
            sms.setReason(element.elementTextTrim("status"));
            sms.setCode(element.elementTextTrim("mobile"));
            sms.setUid(element.elementTextTrim("sysUid"));
        }
    }
}
